import { getUserList, userCount } from "../../../request/api"

const state = {
    userlist: [],
    pageSize: 2,//页面渲染的条数
    pageNum: 1,//页码
    count: 0//总条数
}
const getters = {
    // 获取管理员列表
    getUser(state) {
        return state.userlist
    },
    getSize(state) {
        return state.pageSize
    },
    getCount(state) {
        return state.count
    }
}
const mutations = {
    REQ_USERLIST(state, payload) {
        state.userlist = payload
    },
    REQ_COUNT(state, payload) {
        state.count = payload
    },
    // 封装一个修改页码的事件
    REQ_PAGENUM(state, payload) {
        state.pageNum = payload
    }
}
const actions = {
    getUserAction(context) {
        console.log(context, 'context');
        getUserList({
            size: context.state.pageSize,
            page: context.state.pageNum
        }).then((res) => {
            console.log(res, '////////');
            let list = res.list ? res.list : []

            // 解决删除bug
            if(context.state.pageNum!=1&&list.length==0){
                // 重新触发页码修改
                context.dispatch('changePageAction',context.state.pageNum-1)
            }
            context.commit('REQ_USERLIST',res.list)
        })
    },
    // 获取总条数
    getCountAction({commit}){
        userCount().then(res=>{
            commit('REQ_COUNT',res.list[0].total)
        })
    },
    // 封装一个切换页码并重新触发列表的事件
    changePageAction(context,payload){
        // 修改一下页码
        context.commit('REQ_PAGENUM',payload)
        // 重新触发行动
        context.dispatch('getUserAction')
    }
}

export default {
    state,
    getters,
    mutations,
    actions,
    //命名空间
    namespaced: true,
}